package edu.hawaii.wattwaiter.page.gridinfo;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.extensions.markup.html.tabs.TabbedPanel;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import edu.hawaii.wattwaiter.wattdepotcommands.CarbonFlagSetter;

/**
 * Defines a user interface for the WattWaiter system.  The user interface
 * is viewed and used by the user as a web page.
 * 
 * @author Remy Baumgarten
 * @author Kevin Chiogioji
 * @author David Mau
 * 
 * @version 1.1
 */
public class WattWaiter extends Panel {

  /** Support serialization. */
  private static final long serialVersionUID = 1L;
  /** The current date that is being analyzed by the system and it's commands. */
  private static String date = "";
  /** Tracks if this is the user's first time using WattWaiter. */
  private static boolean firstVisit = true;

  /**
   * Allows the constructor to safely access the firstVisit static boolean.
   * 
   * @return the value of firstVisit
   */
  private boolean toggleFirstVisit() {
    boolean currentValue = firstVisit;
    firstVisit = false;

    return currentValue;
  }

  /**
   * Creates a repeater, <code>ListView</code> that allows for easy use of a
   * <code>List</code>.  The repeater created is used for specific hours.
   * 
   * @param id id field for CSS and Wicket interaction.
   * @param date What date to create the repeater for.
   * @param hourList A list of hours to get.
   * @return A ListView object with hours and flags set correctly.
   */
  private ListView<Hour> getRepeater(String id, String date, List<Hour> hourList) {

    // Repeaters need same labels
    final String label = "label";
    final String hour = "hour";
    ListView<Hour> listview = new ListView<Hour>(id, hourList) {

      private static final long serialVersionUID = 1L;

      @Override
      protected void populateItem(ListItem<Hour> item) {

        // System.out.println("Debug Hour: " + item.getModelObject().getHour());
        // System.out.println("Debug Colr: " + item.getModelObject().getAttribute() + "\n");

        // Insert hour into the hour label
        item.add(new Label(hour, item.getModelObject().getHour()));

        // 0 Flag is Red, set CSS accordingly
        if (item.getModelObject().getAttribute() == 0) {
          Label lab = new Label(label, "");
          lab.add(new SimpleAttributeModifier("id", "red"));
          item.add(lab);
        }
        // Yellow
        else if (item.getModelObject().getAttribute() == 1) {
          Label lab = new Label(label, "");
          lab.add(new SimpleAttributeModifier("id", "yellow"));
          item.add(lab);
        }
        // Green
        else if (item.getModelObject().getAttribute() == 2) {
          Label lab = new Label(label, "");
          lab.add(new SimpleAttributeModifier("id", "green"));
          item.add(lab);
        }
        // No Data
        else {
          Label lab = new Label(label, "No Data");
          lab.add(new SimpleAttributeModifier("id", "red"));
          item.add(lab);
        }
      }
    };
    return listview;
  }

  /**
   * Collects data from WattDepot and packages it into a <code>List</code> of 
   * <code>Hour</code> objects.
   * 
   * @param date The date to query WattDepot with.
   * @param offset What hour to start collecting data about the items.
   * @return The List of Hour objects.
   */
  private List<Hour> getHourList(String date, int offset) {

    // WattDepot CarbonCollector instantiation used to query by date
    // CarbonEmittedCollector data = new CarbonEmittedCollector(defaultServer);
    // List<Double> rawList = data.getList(date);

    // Send raw data to CarbonCollector to get color flags
    CarbonFlagSetter items = new CarbonFlagSetter(date);
    List<Integer> flags = items.getFlags(null);

    // Create list of Hour objects and set flags
    List<Hour> listHour = new ArrayList<Hour>();
    for (int i = offset; i < offset + 12; i++) {
      String hour = null;
      if (offset == 0) {
        if (i == 0) {
          hour = 12 + ":00 am";
        }
        else {
          hour = i + ":00 am";
        }
      }
      if (offset == 12) {
        if (i == 12) {
          hour = 12 + ":00 pm";
        }
        else {
          hour = i % 12 + ":00 pm";
        }
      }

      listHour.add(new Hour(hour, flags.get(i)));
      // System.out.println("Debug Flags: " + flags.get(i));
    }

    return listHour;
  }

  /**
   * The web page content for creating a view of 24 hours of specified day and the
   * flags associated with them.
   */
  public WattWaiter() {
    
    super(TabbedPanel.TAB_PANEL_ID);

    // Get the current Year, Month, and Day.
    // Add CSS to head
    

    add(new FeedbackPanel("feedback"));
    // Define a form object
    Form<String> form = new Form<String>("form");

    // Text field for entering date
    TextField<String> dateInput =
        new TextField<String>("date", new PropertyModel<String>(this, "date"));

    // If it is the user's first visit to this web site,
    if (toggleFirstVisit()) {
      // Set a default value for the date.
      // Obtain the current date.
      Calendar calendar = new GregorianCalendar();
      int currentYear = calendar.get(Calendar.YEAR);
      int currentMonth = calendar.get(Calendar.MONTH) + 1;
      int currentDay = calendar.get(Calendar.DAY_OF_MONTH);

      String[] defaultInput = new String[1];
      defaultInput[0] = currentYear + "-";
      
      // If the current month is single digit, add the extra preceding zero.
      if ( currentMonth < 10 ) {
        defaultInput[0] = defaultInput[0].concat( "0" );
      }
      defaultInput[0] = defaultInput[0].concat( currentMonth + "-" );
      
      // If the current day is single digit, add the extra preceding zero.
      if ( currentDay < 10 ) {
        defaultInput[0] = defaultInput[0].concat( "0" );
      }
      defaultInput[0] = defaultInput[0].concat( currentDay + "" );

      // Set the default input.
      dateInput.setModelValue(defaultInput);
    }

    // Add the date input to the form.
    form.add(dateInput.setRequired(true));

    // Submit Button
    form.add(new Button("Submit") {
      private static final long serialVersionUID = 1L;

      @Override
      public void onSubmit() {
        //setResponsePage(WattWaiter.class);
        info("new date value: " + date);
      }
    });

    add(form);

    // Add ListView to view
    add(getRepeater("leftTable", date, getHourList(date, 0)));
    add(getRepeater("rightTable", date, getHourList(date, 12)));

  }

}
